package cn.tedu.tmall.basic.service.impl;

import cn.tedu.tmall.basic.dao.persist.cache.IDistrictCacheRepository;
import cn.tedu.tmall.basic.dao.persist.repository.IDistrictRepository;
import cn.tedu.tmall.basic.service.IDistrictService;
import cn.tedu.tmall.common.pojo.po.DistrictSimplePO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DistrictService implements IDistrictService {
    @Autowired
    private IDistrictRepository repository;
    @Autowired
    private IDistrictCacheRepository cacheRepository;
    @Override
    public List<DistrictSimplePO> listByParent(Long parentId) {
        List<DistrictSimplePO> cacheDistrictList = cacheRepository.getListByParentId(parentId);
        if(cacheDistrictList.size()==0){
            List<DistrictSimplePO> dbDistrictList = repository.listByParent(parentId);
            cacheRepository.saveListByParentId(parentId,dbDistrictList);
            return dbDistrictList;
        }else {
            return cacheDistrictList;
        }
    }

    @Override
    public void rebuildCache() {
        cacheRepository.deleteDistrictCache();
        Long parentId = 0L;
        List<DistrictSimplePO> list = repository.listByParent(parentId);
        cacheRepository.saveListByParentId(parentId,list);
        for (DistrictSimplePO districtSimplePO : list) {
            cacheRepository.save(districtSimplePO);
            recursion(districtSimplePO);
        }
    }
    //采用递归方法将mysql中数据存入缓存中
    private void recursion(DistrictSimplePO districtSimplePO){
        Long parentId = districtSimplePO.getId();
        List<DistrictSimplePO> list1 = repository.listByParent(parentId);
        if (list1.size()>0){
            cacheRepository.saveListByParentId(parentId,list1);
            for (DistrictSimplePO simplePO : list1) {
                cacheRepository.save(simplePO);
                recursion(simplePO);
            }
        }
    }
}
